package c10_12daimahangshu;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Pattern;

public class hangshu {

    public static void main(String[] args) throws IOException {
        int totalLines = 0;
        String folderPath = "D:\\id\\daima\\shendian"; // 替换为你的文件夹路径
        File folder = new File(folderPath);
        if (folder.exists() && folder.isDirectory()) {
            totalLines = countLinesInFolder(folder);
        } else {
            System.out.println("指定路径不是一个有效的文件夹。");
        }
        System.out.println("文件夹下的.java 文件总代码行数为：" + totalLines);
    }

    private static int countLinesInFolder(File folder) throws IOException {
        int lines = 0;
        File[] files = folder.listFiles();
        if (files!= null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    lines += countLinesInFolder(file);
                } else {
                    if (file.getName().endsWith(".java")||file.getName().endsWith(".html")||file.getName().endsWith(".css")) {
                        lines += countLinesInFile(file);
                    }
                }
            }
        }
        return lines;
    }

    private static int countLinesInFile(File file) throws IOException {
        int lines = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            Pattern commentPattern = Pattern.compile("//.*|/\\*(.|\\R)*?\\*/");
            while ((line = reader.readLine())!= null) {
                // 去除注释
                line = commentPattern.matcher(line).replaceAll("");
                // 去除首尾空格
                line = line.trim();
                if (!line.isEmpty()) {
                    lines++;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }
}

